package business.service.card.impl;

import java.sql.SQLException;
import java.util.List;

import business.entity.Card;
import business.service.card.IEditCardViewService;

import app.MyApplication;

import ui.model.ModelErrorInfo;
import ui.model.card.EditCardViewModel;
import util.data.carddao.ICardDataContext;

public class EditCardViewService implements IEditCardViewService {
//	private IDataContext dct = null;
	private EditCardViewModel viewModel = null;
	private ICardDataContext dct = null;
	
	public EditCardViewService(EditCardViewModel v){
		this.viewModel = v;
		dct = MyApplication.cardDataContext;
	}
	
	@Override
	public boolean save(Card card) {
		viewModel.setCard(card);
		List<ModelErrorInfo> answer = viewModel.verifyModel();
		
		if (answer == null || answer.size() == 0) {
			try {
				dct.update(card);
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
			return true;
		} else {
			viewModel.fireOnUpdated();
			return false;
		}
	}

	@Override
	public boolean add(Card card) {
		viewModel.setCard(card);
		List<ModelErrorInfo> answer = viewModel.verifyModel();
		
		if (answer == null || answer.size() == 0) {
			int id;
			try {
				id = dct.add(card);
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
			card.setId(id);
			return true;
		} else {
			viewModel.fireOnUpdated();
			return false;
		}
	}

	@Override
	public boolean delete(int id) {
		try {
			dct.delete(id);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public Card search(int id) {
		Card card;
		try {
			card = dct.queryById(id);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return card;
	}

}
